package com.hmdp.utils;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.security.PrivateKey;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

/**
 * 单独的计算订单Id的方法
 * 可以注入别的类中，调用nextId方法，得到订单Id
 */
@Component
public class RedisIdWorker {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    //开始时间戳
    private static final long BEGIN_TIMESTAMP = 1640995200;
    //序列号位数
    private static final int CONUT_BTTS = 32;

    public Long nextId(String keyPrefix) {
        //1.生成时间戳
        LocalDateTime now = LocalDateTime.now();
        // 1.1转换为世界时区的秒数
        long second = now.toEpochSecond(ZoneOffset.UTC);
        long timetamp = second - BEGIN_TIMESTAMP;
        //2.生成序列号
        //2.1获取当天日期
        String date = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        //2.2自增
        long count = stringRedisTemplate.opsForValue().increment("icr:" + keyPrefix + ":" + date);
        //3.拼接并返回
        return timetamp << CONUT_BTTS | count;
    }

}
